로딩 중이에요... 🐣
[코담]
웹개발·실전 프로젝트·AI까지, 파이썬·장고의 모든것을 담아낸 강의와 개발 노트
01 데이터 포맷 수정 | ✅ 저자: 이유정(박사)
데이터 포맷 수정이란?
데이터를 분석하기 전에 형식을 통일하고, 다루기 쉬운 형태로 바꾸는 작업.
현실 세계에서 모은 데이터는 다양하고 복잡한 형식으로 되어 있어서,
→ 데이터 분석/모델링 전에 꼭 포맷을 정리해야 합니다!
결측치 채우기 + 데이터 타입 변경
df['age'].fillna(0, inplace=True) # age가 비어있으면 0으로 채움
df['age'] = df['age'].astype('int') # age를 정수(int) 타입으로 바꿈
df['age'].fillna(0, inplace=True)
df['age']
: 나이(age) 열을 가져옵니다..fillna(0)
: 비어 있는 셀(NaN)을0
이라는 숫자로 채웁니다.inplace=True
: 원본 데이터프레임(df)을 직접 수정합니다. 쉽게 말하면 나이 정보가 비어있는 사람은 임시로 0살이라고 적어두는 거예요. 왜 이렇게 하냐면?- 결측치(NaN)가 있는 상태로는 평균 계산, 정렬 등이 에러를 내거나 무시될 수 있기 때문입니다.
- 0살은 실제 값이라기보다 "비어 있음"을 표시하는 기호 값처럼 사용하는 거예요.
df['age'] = df['age'].astype('int')
astype('int')
: 나이 열의 자료형을정수형(int)
으로 바꿉니다.- 원래는 나이가 비어 있었기 때문에
float
형식이었을 수도 있어요. 쉽게 말하면 소수점(예: 30.0)으로 되어 있는 나이를 정수(30)으로 바꾸는 거예요. 왜 이렇게 하냐면? - 나이는 일반적으로 정수로 표현하니까요.
- 정수로 바꾸면 이후에 조건 검색(예:
df[df['age'] > 20]
)이나 통계 처리도 더 간편합니다. - 비어 있는 데이터(NaN)가 들어오면 그 열 전체의 데이터 타입에 따라 자동으로 처리되는데 보통은 소수점(float)형식이 됩니다.
날짜/시간 다루기
df['join_date'] = pd.to_datetime(df['join_date'])
# 문자열을 날짜로 바꿈
df["year"] = df["join_date"].dt.year
df["month"] = df["join_date"].dt.month
df["day"] = df["join_date"].dt.day
df["hour"] = df["join_date"].dt.hour
df["minute"] = df["join_date"].dt.minute
pd.to_datetime()
→ 날짜·시간 문자열을 진짜 날짜형식(datetime)으로 바꿈.dt.year
등 → 날짜에서 연도, 월, 일, 시, 분을 각각 뽑아냅니다.- 이렇게 분리하면 월별 분석, 시간대별 분석 등에 활용할 수 있어요.
실습하기 전체 코드:
import pandas as pd
df = pd.read_csv("csv_files/combined_customers.csv")
df['age'].fillna(0, inplace=True)
df['age'] = df['age'].astype('int')
print(df)
결과:
customer_id name age email \
0 1 Customer1 0 customer1@example.com
1 2 Customer2 0 customer2@example.com
2 3 Customer3 0 customer3@example.com
3 4 Customer4 0 customer4@example.com
4 5 Customer5 0 customer5@example.com
.. ... ... ... ...
495 396 Customer396 54 customer396@example.com
496 397 Customer397 57 customer397@example.com
497 398 Customer398 68 customer398@example.com
498 399 Customer399 29 customer399@example.com
499 400 Customer400 57 customer400@example.com
join_date
0 2023-01-27 06:52:22.275679
1 2023-07-15 06:52:22.275698
2 2023-01-24 06:52:22.275704
3 2023-03-25 06:52:22.275709
4 2023-03-25 06:52:22.275713
.. ...
495 2023-02-09 06:54:12.151607
496 2023-03-25 06:54:12.151613
497 2023-02-19 06:54:12.151618
498 2023-07-18 06:54:12.151624
499 2023-01-22 06:54:12.151629
[500 rows x 5 columns]
fillna(0)
age
에 비어 있는 값(NaN)이 있다면 0으로 채웁니다. 예: 결측치 → 0살 처리
astype('int')
age
열을정수형(int)
으로 바꿉니다. 원래는 NaN 때문에 float형이었을 수 있음
print(df)
- 바뀐
age
값을 포함한 전체 DataFrame을 출력합니다
결과:
age
가 비어있던 행은0
으로 채워짐- 모든
age
값은25.0 → 25
처럼 소수점 없이 깔끔한 정수로 표현됨
join_date
컬럼을 날짜/시간 단위로 분해해서 보여줌
import pandas as pd
df = pd.read_csv("csv_files/combined_customers.csv")
df['join_date'] = pd.to_datetime(df['join_date'])
df["year"] = df["join_date"].dt.year
df["month"] = df["join_date"].dt.month
df["day"] = df["join_date"].dt.day
df["hour"] = df["join_date"].dt.hour
df["minute"] = df["join_date"].dt.minute
print(df)
결과:
customer_id name age email \
0 1 Customer1 NaN customer1@example.com
1 2 Customer2 NaN customer2@example.com
2 3 Customer3 NaN customer3@example.com
3 4 Customer4 NaN customer4@example.com
4 5 Customer5 NaN customer5@example.com
.. ... ... ... ...
495 396 Customer396 54.0 customer396@example.com
496 397 Customer397 57.0 customer397@example.com
497 398 Customer398 68.0 customer398@example.com
498 399 Customer399 29.0 customer399@example.com
499 400 Customer400 57.0 customer400@example.com
join_date year month day hour minute
0 2023-01-27 06:52:22.275679 2023 1 27 6 52
1 2023-07-15 06:52:22.275698 2023 7 15 6 52
2 2023-01-24 06:52:22.275704 2023 1 24 6 52
3 2023-03-25 06:52:22.275709 2023 3 25 6 52
4 2023-03-25 06:52:22.275713 2023 3 25 6 52
.. ... ... ... ... ... ...
495 2023-02-09 06:54:12.151607 2023 2 9 6 54
496 2023-03-25 06:54:12.151613 2023 3 25 6 54
497 2023-02-19 06:54:12.151618 2023 2 19 6 54
498 2023-07-18 06:54:12.151624 2023 7 18 6 54
499 2023-01-22 06:54:12.151629 2023 1 22 6 54
[500 rows x 10 columns]
customer_id
고객 고유 번호
name
고객 이름
age
나이 – 결측치(NaN)도 그대로 있음
email
이메일 주소
join_date
가입 날짜와 시간 (원래 데이터)
year
가입한 연도
month
가입한 월
day
가입한 일
hour
가입한 시간(시)
minute
가입한 분